package com.wardrobe.soa.backend.admin;

import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.wardrobe.handler.CodeHelper;
import com.wardrobe.soa.backend.operator.AdminOperatorBean;
import com.wardrobe.soa.backend.operator.AdminOperatorService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
@RestController
@RequestMapping("/login")
public class SecurityController {

    private static final Logger logger = LoggerFactory.getLogger(SecurityController.class);

    @Resource
    private AdminOperatorService adminOperatorService;

    @RequestMapping("/login")
    public Map<String, Object> login(AdminOperatorBean fromBean, HttpServletRequest request, HttpServletResponse response) {

        final HashMap<String, Object> retMap = Maps.newHashMap();
        try {
            String loginName = fromBean.getNickName();

            final AdminOperatorBean adminOperator = adminOperatorService.findByUsername(loginName);
            if (adminOperator.getId() <= 0) {
                retMap.put("retCode", -1);
                retMap.put("retMsg", "登录信息有误");
                return retMap;
            }

            String encodePwd = CodeHelper.encodePwd(fromBean.getPwd());
            UsernamePasswordToken token = new UsernamePasswordToken(loginName, encodePwd);
            token.setRememberMe(false);

            Subject subject = SecurityUtils.getSubject();
            subject.login(token);

            final Set<String> permissionsByOperatorId = adminOperatorService.getPermissionsByOperatorId(adminOperator);
            final String permissionCode = Joiner.on("#").join(permissionsByOperatorId);
            final Cookie cookie = new Cookie("permission", permissionCode);
            cookie.setMaxAge(3600);
            cookie.setPath("/");
            response.addCookie(cookie);

        } catch (AuthenticationException e) {
            retMap.put("retCode", -1);
            retMap.put("retMsg", "登录信息有误");
            return retMap;
        }

        final AdminOperatorBean operator = adminOperatorService.getCurrentUser();
        HttpSession session = request.getSession();
        session.setAttribute("operator", operator);

        retMap.put("retCode", 1);
        retMap.put("retMsg", "登录成功");
        return retMap;
    }

    @RequestMapping("/noAuth")
    public Map<String, Object> noAuth() {
        final HashMap<String, Object> retMap = Maps.newHashMap();

        retMap.put("retCode", -1);
        retMap.put("retMsg", "没有权限");
        return retMap;
    }

    @RequestMapping("/regist")
    public Map<String, Object> regist(AdminOperatorBean fromBean) {
        final HashMap<String, Object> retMap = Maps.newHashMap();

        final int retCode = adminOperatorService.addAdminOperator(fromBean);
        if (retCode == 1) {
            retMap.put("retCode", 1);
            retMap.put("retMsg", "注册成功");
        } else {
            retMap.put("retCode", retCode);
            retMap.put("retMsg", "注册失败");
        }
        return retMap;
    }

    @RequestMapping("/logout")
    public Map<String, Object> logout(HttpServletRequest request, HttpServletResponse response) {
        final HashMap<String, Object> retMap = Maps.newHashMap();
        final AdminOperatorBean currentUser = adminOperatorService.getCurrentUser();
        if (currentUser != null) {
            logger.info("logout nickname name: {}; adminuser id: {}", currentUser.getNickName(), currentUser.getId());
            SecurityUtils.getSubject().logout();
        }
        for (Cookie c : request.getCookies()) {
            if ("permission".equals(c.getName()) || "JSESSIONID".equals(c.getName())) {
                c.setMaxAge(0);
                c.setPath("/");
                response.addCookie(c);
            }
        }
        retMap.put("retCode", 1);
        retMap.put("retMsg", "退出成功");

        return retMap;
    }


}